package com.wxapp.pay.service.pay.weChat;

import com.wxapp.common.core.filter.except.ThrowMyException;
import com.wxapp.common.util.check.CheckUtil;
import com.wxapp.common.util.feign.DynamicFeignUtil;
import com.wxapp.common.util.http.HttpRequestUtil;
import com.wxapp.pay.api.pojo.enums.listener.RedirectTypeEnum;
import com.wxapp.pay.api.pojo.pojo.vm.pay.PPayVm;
import com.wxapp.pay.api.pojo.pojo.vm.pay.PWechatPayVm;
import com.wxapp.pay.api.pojo.pojo.vo.order.QOrderInfoVo;
import com.wxapp.pay.api.pojo.pojo.vo.payLogs.QPayLogsAddVo;
import com.wxapp.pay.service.event.PayLogsEvent;
import com.wxapp.pay.service.service.PayConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author lgl
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AppWechatPay extends BaseWechatPay {
    private static final String payWay = "WeChatAppPay";
    private final ApplicationEventPublisher publisher;
    private final DynamicFeignUtil dynamicFeignUtil;
    private final PayConfigService payConfigService;
    @Override
    protected String getType() {
        return payWay;
    }


    @Override
    protected PWechatPayVm getRequestVm(QOrderInfoVo qOrderInfoVo) throws ThrowMyException {
        var configs = getConfigs();
        return null;
    }

    @Override
    protected PPayVm dealResponseVm(PWechatPayVm vm) {
        return null;
    }

    @Override
    protected void publicEvent(QPayLogsAddVo vo, ApplicationEvent... event) {
        publisher.publishEvent(new PayLogsEvent(this,"",vo));
        if (CheckUtil.isNullArray(event)) {
            return;
        }
        for (ApplicationEvent e : event) {
            publisher.publishEvent(e);
        }
    }

    @Override
    protected Boolean checkResponse(PPayVm<String> vm, PWechatPayVm vp) {
        return null;
    }

    @Override
    protected Boolean redirect(QOrderInfoVo vo) {
        try {
            if (vo.getRequestType()== RedirectTypeEnum.HTTP_REQUEST){
                HttpRequestUtil.request(vo.getHttpRedirect());
            }else if (vo.getRequestType()== RedirectTypeEnum.FEIGN_REQUEST){
                dynamicFeignUtil.executeApi(vo.getFeignRedirect());
            }else {
                return false;
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从数据库中获取支付配置
     */
    private Map<String, String> getConfigs() throws ThrowMyException {
        var config = payConfigService.getConfigsByCode(payWay);
        if (CheckUtil.isNullMap(config.getData())) {
            throw new ThrowMyException("没有找到支付方式");
        }
        return config.getData();
    }
}
